package com.kly.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kly.domain.dto.spaceuser.SpaceUserAddRequest;
import com.kly.domain.dto.spaceuser.SpaceUserQueryRequest;
import com.kly.domain.entity.Space;
import com.kly.domain.entity.SpaceUser;
import com.kly.domain.entity.User;
import com.kly.domain.enums.SpaceRoleEnum;
import com.kly.domain.vo.SpaceUserVO;
import com.kly.domain.vo.UserVO;
import com.kly.domain.vo.space.SpaceVO;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.exception.ThrowUtils;
import com.kly.mapper.SpaceUserMapper;
import com.kly.service.SpaceService;
import com.kly.service.SpaceUserService;
import com.kly.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author admin
 * @description 针对表【space_user(空间用户关联)】的数据库操作Service实现
 * @createDate 2025-03-18 21:52:23
 */
@Service
@RequiredArgsConstructor
public class SpaceUserServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser>
        implements SpaceUserService {

    private final UserService userService;

    private final SpaceService spaceService;




    @Override
    public void validSpaceUser(SpaceUser spaceUser, boolean add) {
        ThrowUtils.throwIf(spaceUser == null, ErrorCode.PARAMS_ERROR);
        // 创建时，空间 id 和用户 id 必填
        Long spaceId = spaceUser.getSpaceId();
        Long userId = spaceUser.getUserId();
        if (add) {
            ThrowUtils.throwIf(ObjectUtil.hasEmpty(spaceId, userId), ErrorCode.PARAMS_ERROR);
            User user = userService.getById(userId);
            ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR, "用户不存在");
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 校验空间角色
        String spaceRole = spaceUser.getSpaceRole();
        SpaceRoleEnum spaceRoleEnum = SpaceRoleEnum.getEnumByValue(spaceRole);
        if (spaceRole != null && spaceRoleEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间角色不存在");
        }
    }


    @Override
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceUserQueryRequest) {
        ThrowUtils.throwIf(spaceUserQueryRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        Long id = spaceUserQueryRequest.getId();
        Long spaceId = spaceUserQueryRequest.getSpaceId();
        Long userId = spaceUserQueryRequest.getUserId();
        String spaceRole = spaceUserQueryRequest.getSpaceRole();
        QueryWrapper<SpaceUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotNull(spaceId), "space_id", spaceId);
        queryWrapper.eq(ObjUtil.isNotNull(userId), "user_id", userId);
        queryWrapper.eq(ObjUtil.isNotNull(spaceRole), "space_role", spaceRole);

        return queryWrapper;
    }

    @Override
    public SpaceUserVO getSpaceUserVO(SpaceUser spaceUser, HttpServletRequest request) {
        // 对象转封装类
        SpaceUserVO spaceUserVO = SpaceUserVO.objToVo(spaceUser);
        // 关联查询用户信息
        Long userId = spaceUser.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVo(user);
            spaceUserVO.setUserVO(userVO);
        }
        // 关联查询空间信息
        Long spaceId = spaceUser.getSpaceId();
        if (spaceId != null && spaceId > 0) {
            Space space = spaceService.getById(spaceId);
            SpaceVO spaceVO = spaceService.getSpaceVO(space, request);
            spaceUserVO.setSpaceVO(spaceVO);
        }
        return spaceUserVO;
    }


    @Override
    public List<SpaceUserVO> listSpaceUserVOList(List<SpaceUser> spaceUserList) {
        if (CollUtil.isEmpty(spaceUserList)) {
            return Collections.emptyList();
        }
        // 生成spaceUserVOList
        List<SpaceUserVO> spaceUserVOList = spaceUserList.stream().map(SpaceUserVO::objToVo).collect(Collectors.toList());
        // 生成userIdList
        Set<Long> userIdList = spaceUserList.stream().map(SpaceUser::getUserId).collect(Collectors.toSet());
        // 生成spaceIdList
        Set<Long> spaceIdList = spaceUserList.stream().map(SpaceUser::getSpaceId).collect(Collectors.toSet());
        // 查询用户信息
        Map<Long, List<User>> idUserMap = userService.listByIds(userIdList).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 查询空间信息
        Map<Long, List<Space>> idSpaceMap = spaceService.listByIds(spaceIdList).stream()
                .collect(Collectors.groupingBy(Space::getId));
        spaceUserVOList.forEach(spaceUserVO -> {
            Long userId = spaceUserVO.getUserId();
            if (idUserMap.containsKey(userId)) {
                List<User> userList = idUserMap.get(userId);
                User user = userList.get(0);
                UserVO userVO = userService.getUserVo(user);
                spaceUserVO.setUserVO(userVO);
            }
            Long spaceId = spaceUserVO.getSpaceId();
            if (idSpaceMap.containsKey(spaceId)) {
                List<Space> spaceList = idSpaceMap.get(spaceId);
                Space space = spaceList.get(0);
                SpaceVO spaceVO = spaceService.getSpaceVO(space, null);
                spaceUserVO.setSpaceVO(spaceVO);
            }
        });
        return spaceUserVOList;
    }

    @Override
    public Long addSpaceUser(SpaceUserAddRequest spaceUserAddRequest, User loginUser) {
        // 1. 校验参数
        ThrowUtils.throwIf(spaceUserAddRequest == null, ErrorCode.PARAMS_ERROR);
        SpaceUser spaceUser = BeanUtil.copyProperties(spaceUserAddRequest, SpaceUser.class);
        // 校验合法性
        validSpaceUser(spaceUser, true);
        // 设置角色默认值
        spaceUser.setSpaceRole(SpaceRoleEnum.VIEWER.getValue());
        // 2. 插入数据
        boolean save = this.save(spaceUser);
        ThrowUtils.throwIf(!save, ErrorCode.OPERATION_ERROR, "添加失败");
        return spaceUser.getId();
    }
}




